from Organization.models import *
from django.db.models import Q, F

# Create your models here.
'''
    RoleManager:权限管理器

'''


class RoleManager(models.Manager):
    def create(self, roleName):
        role = self.model()
        role.roleName = roleName
        role.save()
        return role

'''
    Role:权限表
         roleName：角色名   
'''


class Role(models.Model):
    roleName = models.CharField(max_length=10)

    roles = RoleManager()

    class Meta:
        db_table = 'Role'


'''
    UserManager:用户管理器

'''


class UserManager(models.Manager):
    def create(self, username, password, email, statffs):
        user = self.model()
        user.username = username
        user.password = password
        user.email = email
        user.staffs_id = statffs
        user.save()
        return user

    def findRegister(self, username):
        if len(self.filter(username=username)) > 0:
            return True
        else:
            return False

    def findLogin(self, username, password):
        if len(self.filter(username=username).filter(password=password)) > 0:
            return True
        else:
            return False

    def remove(self, id):
        self.filter(pk = int(id)).update(isDelete = True)
        users = self.filter(isDelete = False).values()
        return users

    def update(self, id, role):
        if role == "1":
            self.filter(pk = int(id)).update(roles = 1)
        else:
            self.filter(pk = int(id)).update(roles = 2)
        users = self.filter(pk = int(id)).values()
        return users

    def query(self, id):
        users = self.filter(Q(id__contains = id)|Q(staffs__name__contains = id)|Q(username__contains = id)|Q(email__contains = id)|Q(roles__roleName__contains = id))
        return users
'''
    User:用户表
         username：用户名
         password：密码
         email：邮箱
         isDelete：是否删除
         staffs：员工id
         roles：角色id 
'''


class User(models.Model):
    username = models.CharField(max_length=20)
    password = models.CharField(max_length=64)
    email = models.EmailField()
    isDelete = models.BooleanField(default=False)
    staffs = models.ForeignKey(Staff, on_delete=models.CASCADE)
    roles = models.ForeignKey(Role, on_delete=models.CASCADE, default=1)

    users = UserManager()

    class Meta:
        db_table = 'User'

